package com.core.springSecurity.common;

import com.common.emums.UserType;
import com.common.utils.NetworkUtils;
import com.core.springSecurity.model.LoginUserDetails;
import com.model.pojo.sys.SysUser;
import com.service.sys.SysUserService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: zql
 * @Description: 游客信息管理
 * @Data: 8:25 2021/7/26
 */
@Slf4j
public class AnonymousHolder {


    static  AntPathMatcher antPathMatcher =new AntPathMatcher();

    static SysUserService sysUserService;


    public static void setSysUserService(SysUserService sysUserService) {
        AnonymousHolder.sysUserService = sysUserService;
    }

    public static void addMatcher(String ... servletPaths){
         antPathMatcher.addMatcher(servletPaths);
    }

    public static boolean matcher(String servletPath){
        return antPathMatcher.matcher(servletPath);
    }

    private static final ThreadLocal<LoginUserDetails> anonymousHolder = new ThreadLocal<>();



    public static LoginUserDetails getLoginUserDetails() {
        LoginUserDetails ctx = anonymousHolder.get();
        if (ctx == null) {
            log.error("游客不存在");
            //游客不存在
        }
        return ctx;
    }

    private static SysUser createSysUser(String name,String ip){
        SysUser sysUser = new SysUser();
        sysUser.setName(name);
        sysUser.setFullName("游客");
        sysUser.setPassword("");
        sysUser.setSysDeptId(1L);
        sysUser.setUserType(UserType.ANONYMOUS.getCode());
        sysUser.setIp(ip);
        sysUserService.register(sysUser);
        return  sysUser;
    }

    public static void setLoginUserDetails(LoginUserDetails ctx){
        //记录到线程
        anonymousHolder.set(ctx);
    }



    public static void setLoginUserDetails(HttpServletRequest request){
        //直接从数据库读取用户信息
        String ip=NetworkUtils.getIPAddress(request);
        String name = FingerprintUtils.getFingerprintDeviceID();
        SysUser sysUser;
        if(sysUserService.hasName(name)) {
            sysUser = sysUserService.getByName(name);
        }
        else{
            sysUser = createSysUser(name,ip);
        }

        LoginUserDetails ctx = createEmptyLoginUserDetails();
        ctx.setUser(sysUser);
        ctx.setIpaddr(ip);
        //记录到线程
        anonymousHolder.set(ctx);
    }

    public static LoginUserDetails createEmptyLoginUserDetails() {
        return new LoginUserDetails();
    }

}
